package com.getsendsocial.GetSendSocial.Database;

import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.widget.Toast;

import com.getsendsocial.GetSendSocial.Activity.ABSTabsViewPagerActivity;
import com.getsendsocial.GetSendSocial.Model.FraseModel;


public class DbActivity extends AsyncTask<Void, Void, String> {
	private Context context;
	private GSDatabase db;

	public DbActivity(Context ctx) {
		context = ctx;
	}

	@Override
	protected void onPostExecute(String s){
		super.onPostExecute(s);
		ABSTabsViewPagerActivity.dialog.dismiss();
		if (s.equals("SERVERERROR")){
			Toast.makeText(ABSTabsViewPagerActivity.c, "Errore di comunicazione con il server", Toast.LENGTH_SHORT).show();
		}else if(s.equals("DBERROR")){
			Toast.makeText(ABSTabsViewPagerActivity.c, "Errore aggiornamento database locale", Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(ABSTabsViewPagerActivity.c, "Il database è stato aggiornato!", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected String doInBackground(Void... arg0) {
		db = new GSDatabase(context);
		db.open();
		List<NameValuePair> params = new LinkedList<NameValuePair>();

		Cursor funny = db.toSync("FunnyTable");
		Cursor congr = db.toSync("CongrTable");
		int funnyCount = funny.getCount();
		int congrCount = congr.getCount();

		params.add(new BasicNameValuePair("idFunny", Integer.toString(funnyCount)));
		params.add(new BasicNameValuePair("idCongr",Integer.toString(congrCount)));

		String paramString = URLEncodedUtils.format(params, "utf-8");
		String url = "http://www.getsenddev.appspot.com/getFrase?" + paramString;

		RestTemplate restTemplate = new RestTemplate();
		restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
		FraseModel[] frases= null;
		try{
			frases = restTemplate.getForObject(url, FraseModel[].class);
		}catch(Exception e){
			return "SERVERERROR";
		}

		String result = db.insertFrase(frases);
		db.close();

		return result;
	}
}
